<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/5/12
 * Time: 11:35
 */

namespace common\logics\businvite;

use common\widgets\Tool;
use Yii;
use yii\base\BaseObject;

class BusInviteLogic extends BaseObject implements IBusInvite
{
    /** @var \common\sources\read\buyuser\BuyUserAccess  $RBuyUserAccess **/
    private $RBuyUserAccess;
    /** @var \common\sources\read\taskorder\TaskOrderAccess $RTaskOrderAccess **/
    private $RTaskOrderAccess;
    /** @var \common\sources\read\pepperrecord\PepperRecordAccess $RPepperRecordAccess **/
    private $RPepperRecordAccess;

    public function init()
    {
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        $this->RPepperRecordAccess = Yii::$container->get("RPepperRecordAccess");
        parent::init();
    }

    public function getBusInvite($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家id不能为空");
        }
        if(empty($data['type']))
        {
            return Tool::returnJson([],402,"类型不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        if(md5($data['type'].$data['bus_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],405,"安全码不正确");
        }
        $bususer = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($bususer))
        {
            return Tool::returnJson([],406,"账号信息不存在");
        }
        if($bususer['role'] == 1)
        {
            return Tool::returnJson([],407,"非商家账号");
        }
        $count = 0;
        $monthCount  =0;
        $profit = 0;
        if($data['type'] == 1)//1.邀请商家
        {
            $count = $this->RBuyUserAccess->getInviteCount(["buy_id" => $data['bus_id'],"role" =>2]);
            $monthCount = $this->RBuyUserAccess->getInviteMonthCount(['buy_id' => $data['bus_id'],"role" => 2,"month_time"=>strtotime(date('Y-m-d', strtotime("-30 day")))]);
            $profit = 0;
        }else if($data['type'] ==2)// 2.邀请买手
        {
            $count = $this->RBuyUserAccess->getInviteCount(["buy_id" => $data['bus_id'],"role" =>1]);
            $monthCount = $this->RBuyUserAccess->getInviteMonthCount(['buy_id' => $data['bus_id'],"role" => 1,"month_time"=>strtotime(date('Y-m-d', strtotime("-30 day")))]);
            $profit = 0;
        }
        $arr = [
            "count" => $count,
            "month_count" => $monthCount,
            "profit" => $profit,
        ];
        return Tool::returnJson($arr,200,"成功");
    }
    //收徒奖励
    public function getApprent($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if(md5($data['bus_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,"安全码不正确");
        }
        $count = $this->RBuyUserAccess->getChildrentCount($data);
        $list = [];
        if($count >0)
        {
            $list = $this->RBuyUserAccess->getChildrens($data);
            foreach ($list as &$item)
            {
                $item['order'] = $item['count'];
                $item['reward'] = 0;
                $bus_arr_list = $this->RBuyUserAccess->getInviteList(['buy_id'=> $data['bus_id'],"reg_day" => $item['days']]);
                if(count($bus_arr_list) >0)
                {
                    foreach ($bus_arr_list as &$busItem)
                    {
                        $busItem['role_name'] = $busItem['role'] == 2 ? "商家":($busItem['role'] ==1 ? "买手":"未知角色");
                        $busItem['status_name'] = "未奖励";
                        $busItem['duration'] = "无";
                        $busItem['commission'] = 0;
                        $busItem['contact'] = $busItem['phone'];
                        $busItem['phone'] = $this->func_substr_replace($busItem['phone'],"*",2,mb_strlen($busItem['phone'],"utf-8")-4);
                    }
                }
                $item['busUsers'] = $bus_arr_list;
            }
        }
        return Tool::returnJson(["list" => $list,"count"=> $count,"page_num"=> $data['page_num'],"limit" => $data['limit']]);
    }
    //任务奖励
    public function getTaskReward($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if(md5($data['bus_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,"安全码不正确");
        }
        //所有邀请的人
        $inviter = $this->RBuyUserAccess->getInviters(['buy_id' => $data['bus_id'],"role" => 1]);
        $task_order_list = [];
        $task_order_count= 0;
        if(count($inviter)>0)
        {
            $buy_arr = array_column($inviter,"id");
            $buy_ids = implode(",",$buy_arr);
            $task_order_count = $this->RTaskOrderAccess->getTaskOrderByBuyIdCount(['buy_ids'=> $buy_ids,"order_status" => '1,2,3,4,5,6,7,8,9,12,13']);
            if($task_order_count>0)
            {
                $task_order_list = $this->RTaskOrderAccess->getTaskOrderByBuyID(['buy_ids'=> $buy_ids,"order_status" => '1,2,3,4,5,6,7,8,9,12,13']);
                foreach ($task_order_list as &$item)
                {
                    //完成任务数量
                    $item['complete_count'] = $this->RTaskOrderAccess->getTaskOrderByBuyIdCount(['buy_ids'=> $buy_ids,"order_status" => '8,12,13']);
                    //获取奖励
                    $reward = $this->RPepperRecordAccess->getTaskOrderAward(["buy_id"=>$data['bus_id'],"task_time" =>$item['days'] ]);
                    $item['reward'] = isset($reward['income']) ? $reward['income'] :0.00;
                    //第二层
                    $sort_task_arr = $this->RTaskOrderAccess->getTaskOrderSort(['days' => $item['days'],"buy_id"=> $data['bus_id']]);
                    if(count($sort_task_arr)>0)
                    {
                        foreach ($sort_task_arr as &$sortitem)
                        {
                            //邀请人手机
                            $buyUser = $this->RBuyUserAccess->getBuyUserInfo($sortitem['buy_id']);
                            $sortitem['phone'] = $this->func_substr_replace($buyUser['phone'],"*",2,6);
                            //接单数量
                            $task_count = $this->RTaskOrderAccess->getTaskOrderByBuyIdCount(['buy_ids'=> $sortitem['buy_id'],"order_status" => '1,2,3,4,5,6,7,8,9,12,13']);
                            $sortitem['buy_task_count'] = $task_count;
                            //完成单数
                            $buy_complete_count = $this->RTaskOrderAccess->getTaskOrderByBuyIdCount(['buy_ids'=> $sortitem['buy_id'],"order_status" => '8,12,13']);
                            $sortitem['buy_complete_count'] = $buy_complete_count;
                            //完成任务单奖励
                            $invited_task_order = $this->RTaskOrderAccess->getTaskOrderPepper(['buy_id'=> $data['bus_id']]);
                            $sortitem['complete_task_order'] = $invited_task_order;
                        }
                    }
                    $item['sort_task'] = $sort_task_arr;
                }

            }
        }
        return Tool::returnJson([
            "list" => $task_order_list,
            "task_order_count" => $task_order_count,
            "page_num" => $data['page_num'],
            "limit" => $data['limit'],
        ],200,"成功");
    }


    /**
     * 隐藏标题
     *  $replacement 替换符号
     *  $start 隐藏开始
     *  $sublen  隐藏长度
     **/
    private function func_substr_replace($str, $replacement = '*', $start = 1, $length = 3)
    {
        $len = mb_strlen($str, 'utf-8');
        if ($len > intval($start + $length)) {
            $str1 = mb_substr($str, 0, $start, 'utf-8');
            $str2 = mb_substr($str, intval($start + $length), NULL, 'utf-8');
        } else {
            $str1 = mb_substr($str, 0, 1, 'utf-8');
            $str2 = mb_substr($str, $len - 1, 1, 'utf-8');
            $length = $len - 2;
        }
        $new_str = $str1;
//        for ($i = 0; $i < $length; $i++) {
//            $new_str .= $replacement;
//        }
        $new_str .= $replacement.$replacement.$replacement.$replacement.$replacement.$replacement;
        $new_str .= $str2;
        return $new_str;
    }

}